<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <title>用户管理</title>
    <link rel="icon" href="${pageContext.request.contextPath}/favicon.ico" type="image/ico">
    <meta name="keywords" content="LightYear,LightYearAdmin,光年,后台模板,后台管理系统,光年HTML模板">
    <meta name="description" content="Light Year Admin V4是一个后台管理系统的HTML模板，基于Bootstrap v4.4.1。">
    <meta name="author" content="yinqi">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/css/icons.min.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/js/jquery-confirm/jquery-confirm.min.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/css/animate.min.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/css/style.min.css" rel="stylesheet">
</head>

<body>
<div class="container-fluid p-t-15" id="app">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-toolbar d-flex flex-column flex-md-row">
                    <div class="toolbar-btn-action">
                        <button class="btn btn-primary m-r-5"
                                data-toggle="modal"
                                data-target="#addModalChange"><i
                                class="mdi mdi-plus"></i> 新增
                        </button>

                        <button class="btn btn-danger" @click="deleteUser"><i class="mdi mdi-window-close"></i> 删除
                        </button>
                    </div>

                    <%--添加用户 模态框--%>
                    <div class="modal fade" id="addModalChange" tabindex="-1" role="dialog"
                         aria-labelledby="exampleModalChangeLabel" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-body">
                                    <form class="was-validated" novalidate>
                                        <div class="mb-3">
                                            <label for="username">用户名</label>
                                            <input v-model="addUser.userName" type="text" class="form-control"
                                                   id="username" required>
                                            <div class="invalid-feedback">请输入用户名</div>
                                        </div>
                                        <div class="form-group mb-3">
                                            <label for="sex">性别</label>
                                            <select id="sex" v-model="addUser.sex" class="custom-select" required>
                                                <option value="">选择性别</option>
                                                <option value="女">女</option>
                                                <option value="男">男</option>
                                            </select>
                                            <div class="invalid-feedback">请选择一项</div>
                                        </div>
                                        <div class="mb-3">
                                            <label for="password">密码</label>
                                            <input v-model="addUser.password" type="text" class="form-control"
                                                   id="password" required>
                                            <div class="invalid-feedback">请输入密码</div>
                                        </div>
                                        <div class="mb-3">
                                            <label for="phone">手机号码</label>
                                            <input v-model="addUser.phone" type="text" class="form-control" id="phone"
                                                   required>
                                            <div class="invalid-feedback">请手机号</div>
                                        </div>

                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                                    <button type="button" class="btn btn-primary" @click="add" id="addUser">添加
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <%--修改用户--%>
                    <div class="modal fade" id="editModalChange" tabindex="-1" role="dialog"
                         aria-labelledby="exampleModalChangeLabel" aria-hidden="true">
                        <div class="modal-dialog" role="document">
                            <div class="modal-content">
                                <div class="modal-body">
                                    <form class="was-validated" novalidate>
                                        <div class="mb-3">
                                            <label for="username">用户名</label>
                                            <input type="text" class="form-control" v-model="editUser.userName"
                                                   id="editusername"
                                                   required>
                                            <div class="invalid-feedback">请输入用户名</div>
                                        </div>
                                        <div class="form-group mb-3">
                                            <label for="sex">性别</label>
                                            <select v-model="editUser.sex" id="editsex" class="custom-select" required>
                                                <option value="">选择性别</option>
                                                <option value="女">女</option>
                                                <option value="男">男</option>
                                            </select>
                                            <div class="invalid-feedback">请选择一项</div>
                                        </div>
                                        <div class="mb-3">
                                            <label for="password">密码</label>
                                            <input v-model="editUser.password" type="text" class="form-control"
                                                   id="editpassword" required>
                                            <div class="invalid-feedback">请输入密码</div>
                                        </div>
                                        <div class="mb-3">
                                            <label for="phone">手机号码</label>
                                            <input v-model="editUser.phone" type="text" class="form-control"
                                                   id="editphone" required>
                                            <div class="invalid-feedback">请手机号</div>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                                    <button type="button" class="btn btn-primary" data-target="#editModalChange"
                                            @click="editHandle">修改
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <%--搜索框--%>
                    <form class="search-bar ml-md-auto" method="get" action="#!" role="form">
                        <input type="hidden" name="search_field" id="search-field" value="title"/>
                        <div class="input-group ml-md-auto">
                            <input type="text" v-model="queryUser.username" class="form-control"  placeholder="请输入用户名">
                                <button class="btn btn-success" @click="getQueryUserList"><i
                                        class="mdi mdi-account-search"></i>
                                    查询
                                </button>
                        </div>
                    </form>
                </div>
                <div class="card-body">

                    <%--表格--%>
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                            <tr>
                                <th>
                                    <div class="custom-control custom-checkbox">
                                        <input type="checkbox"
                                               v-model="selectedUser"
                                               @change="toggleAll">
                                    </div>
                                </th>
                                <th>编号</th>
                                <th>用户名</th>
                                <th>性别</th>
                                <th>密码</th>
                                <th>电话号码</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr v-for="(item, index) in rows" :key="index">
                                <td>
                                    <div class="custom-control custom-checkbox">
                                                <input type="checkbox" v-model="selectedUserIds" :value="item.id">
                                    </div>
                                </td>
                                <td>{{item.id}}</td>
                                <td>{{item.userName}}</td>
                                <td>{{item.sex}}</td>
                                <td>{{item.password}}</td>
                                <td>{{item.phone}}</td>
                                <td>
                                    <div class="btn-group">
                                        <button class="btn btn-outline-dark"
                                                @click="getEditUser(item.id)"
                                                style="margin: 5px">编辑
                                        </button>
                                        <button class="btn btn-outline-danger"
                                                @click="deleteUserById(item.id)"
                                                style="margin: 5px">删除
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <%--分页--%>
                    <nav>
                        <ul class="pagination">
                            <template v-for="i in pages">
                                <%--<li class="page-item disabled">
                                <a class="page-link" href="#!" tabindex="-1">上一页</a>
                            </li>--%>
                                <li v-if="i==pageIndex" class="page-item active">
                                    <a class="page-link" onclick="getUserList(this)">{{i}}</a>
                                </li>
                                <li v-else
                                    class="page-item"><a class="page-link" onclick="getUserList(this)">{{i}}</a></li>
                                <%--<li class="page-item">
                                    <a class="page-link" href="#!">下一页</a>
                                </li>--%>
                            </template>
                        </ul>
                    </nav>
                </div>
            </div>
        </div>
    </div>

</div>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/popper.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/lyear-loading.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bootstrap-notify.min.js"></script>
<script type="text/javascript"
        src="${pageContext.request.contextPath}/js/jquery-confirm/jquery-confirm.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/main.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/lightyear.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/bootstrap-notify.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/vue.js"></script>
<script type="text/javascript">
    // 添加用户 模态框
    $('#addModalChange').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var recipient = button.data('whatever');
        var modal = $(this);
        modal.find('.modal-title').text('New message to ' + recipient);
        modal.find('.modal-body input').val(recipient);
    })

    var vm = new Vue({
        el: '#app',
        data: {
            total: 0,
            rows: '',
            pages: 0,
            pageIndex: 1,
            queryUser:{
                username:''
            },
            addUser: {
                id: 0,
                password: "",
                phone: "",
                sex: "",
                userName: ""
            },
            editUser: {
                id: 0,
                password: "",
                phone: "",
                sex: "",
                userName: ""
            },

            selectedUser: false,
            selectedUserIds: [],
        },
        created() {
            // 分页查询
            this.getQueryUserList()
        },
        methods: {
            getQueryUserList() {
                // 请求加载
                $.post('${pageContext.request.contextPath}/admin/user/search', {
                    userName:this.queryUser.username,
                    pageIndex: this.pageIndex,
                    pageSize: 8
                }, response => {
                    this.pages = response.data.pages;
                    this.total = response.data.total;
                    this.rows = response.data.rows;
                })
            },

            deleteUserById(id) {
                $.post("${pageContext.request.contextPath}/admin/user/del/" + id, {
                    id: id
                })

                setTimeout(() => {
                    // 请求加载
                    this.getQueryUserList()
                    lightyear.notify("操作成功", 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'center');
                }, 500)

            },

            add() {
                // console.log(controls, id)
                var username = $('#username').val()
                var sex = $('#sex').val()
                var password = $('#password').val()
                var phone = $('#phone').val()

                // console.log(sex)
                $.post('${pageContext.request.contextPath}/admin/user/add', {
                    userName: username,
                    sex: sex,
                    password: password,
                    phone: phone
                })

                setTimeout(() => {
                    // 请求加载
                    this.getQueryUserList()
                    this.addUser = {
                        id: 0,
                        password: "",
                        phone: "",
                        sex: "",
                        userName: ""
                    }
                    $('#addModalChange').modal('hide')
                    lightyear.notify("操作成功", 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'center');
                }, 500)

            },

            getEditUser(id) {

                $.get('${pageContext.request.contextPath}/admin/user/' + id,
                    resp => {
                        // console.log(resp)
                        this.editUser = resp.data.data
                    })
                $('#editModalChange').modal('show')
            },

            editHandle() {
                $.post('${pageContext.request.contextPath}/admin/user/update',
                    {
                        id: this.editUser.id,
                        userName: this.editUser.userName,
                        sex: this.editUser.sex,
                        password: this.editUser.password,
                        phone: this.editUser.phone,
                    },
                    resp => {
                        console.log(resp)
                    }
                )
                // console.log(this.editUser);
                setTimeout(() => {
                    // 请求加载
                    this.getQueryUserList()
                    $('#editModalChange').modal('hide')
                    lightyear.notify("操作成功", 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'center');
                }, 500)

            },

            toggleAll() {
                this.selectedUserIds = this.selectedUser ? this.rows.map(item => item.id) : [];
            },

            deleteUser() {
                console.log(this.selectedUserIds)
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/user/delete",
                    data: JSON.stringify(this.selectedUserIds),
                    type: "POST",
                    dataType: "json",
                    contentType: 'application/json;charset=utf-8',//这个必须是这个格式
                    success: resp => {
                        console.log(resp)
                    },
                    error: error => {
                        console.log(error)
                    }
                })

                setTimeout(()=>{
                    this.getQueryUserList()
                    this.selected=false
                    lightyear.notify("操作成功", 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'center');
                },500)

            },

        }
    })

    // 分页函数
    function getUserList(li) {
        var pageIndex = li.innerText
        console.log("pageIndex：", pageIndex)
        vm.pageIndex = pageIndex

        // 请求加载
        $.post('${pageContext.request.contextPath}/admin/user/search', {
            userName:vm.queryUser.username,
            pageIndex: vm.pageIndex,
            pageSize: 8
        }, function (response) {
            vm.pages = response.data.pages;
            // vm.pageIndex=response.data.pageIndex;
            vm.total = response.data.total;
            vm.rows = response.data.rows;
        })
    }


    /*$(document).ready(function () {
        // 分页查询
        $.post('<%--${pageContext.request.contextPath}--%>/admin/search', {
            pageIndex: 1,
            pageSize: 5
        }, response => {
            vm.pages = response.data.pages;
            // vm.pageIndex=response.data.pageIndex;
            vm.total = response.data.total;
            vm.rows = response.data.rows;
        })

        // 添加用户
        $('#addUser').click(function () {

            var username = $('#username').val()
            var sex = $('#sex').val()
            var password = $('#password').val()
            var phone = $('#phone').val()

            if (sex === "") {
                sex = "男"
            }
            if (sex === "0") {
                sex = "女"
            } else if (sex === "1") {
                sex = "男"
            }
            console.log(sex)
            $.post('<%--${pageContext.request.contextPath}--%>/admin/addUser', {
                userName: username,
                sex: sex,
                password: password,
                phone: phone
            }, response => {
                console.log(response)
                if (response.code === 200) {
                    lightyear.notify(response.msg, 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'center');
                    $('#exampleModalChange').modal('hide')
                    <%--location.href = "${pageContext.request.contextPath}/admin/index"--%>
                } else {
                    lightyear.notify(response.msg, 'danger', 5000, 'mdi mdi-emoticon-happy', 'top', 'center');
                }
            })

        })
    })*/

</script>
<%--<script type="text/javascript">
  $(function(){
    $('.search-bar .dropdown-menu a').click(function() {
      var field = $(this).data('field') || '';
      $('#search-field').val(field);
      $('#search-btn').html($(this).text());
    });

    // 通用ajax post请求
    jQuery(document).delegate('.ajax-post', 'click', function(){
      var self        = jQuery(this), tips = self.data('tips'), ajax_url = self.attr("href") || self.data("url");
      var target_form = self.attr('target-form');
      var text        = self.data('tips');
      var form        = jQuery('form[name="'+ target_form +'"]');

      if (form.length == 0) {
        form = jQuery('.' + target_form);
      }

      var form_data = form.serialize();
      if ('submit' == self.attr('type') || ajax_url) {
        if (void 0 == form.get(0)) return false;

        // 如果节点是FORM表单
        if ('FORM' == form.get(0).nodeName) {
          ajax_url = ajax_url || form.get(0).action;

          // 确认提交
          if (self.hasClass('confirm')) {
            $.confirm({
              title: '',
              content: tips || '确认要执行该操作吗？',
              type: 'orange',
              typeAnimated: true,
              buttons: {
                confirm: {
                  text: '确认',
                  btnClass: 'btn-blue',
                  action: function() {
                    var loader = $('body').lyearloading({
                      opacity: 0.2,
                      spinnerSize: 'lg'
                    });
                    self.attr('autocomplete', 'off').prop('disabled', true);
                    ajaxPostFun(self, ajax_url, form_data, loader);
                  }
                },
                cancel: {
                  text: '取消',
                  action: function() {}
                }
              }
            });
            return false;
          } else {
            self.attr("autocomplete", "off").prop("disabled", true);
          }
        } else if ('INPUT' == form.get(0).nodeName || 'SELECT' == form.get(0).nodeName || 'TEXTAREA' == form.get(0).nodeName) {
          // 复选框判断是否有选择项
          if (form.get(0).type == 'checkbox' && form_data == '') {
            showNotify('请选择您要操作的数据', 'danger');
            return false;
          }

          if (self.hasClass('confirm')) {
            $.confirm({
              title: '',
              content: tips || '确认要执行该操作吗？',
              type: 'orange',
              typeAnimated: true,
              buttons: {
                confirm: {
                  text: '确认',
                  btnClass: 'btn-blue',
                  action: function() {
                    var loader = $('body').lyearloading({
                      opacity: 0.2,
                      spinnerSize: 'lg'
                    });
                    self.attr('autocomplete', 'off').prop('disabled', true);

                    ajaxPostFun(self, ajax_url, form_data, loader);
                  }
                },
                cancel: {
                  text: '取消',
                  action: function() {}
                }
              }
            });
            return false;
          } else {
            self.attr("autocomplete", "off").prop("disabled", true);
          }
        } else {
          if (self.hasClass('confirm')) {
            $.confirm({
              title: '',
              content: tips || '确认要执行该操作吗？',
              type: 'orange',
              typeAnimated: true,
              buttons: {
                confirm: {
                  text: '确认',
                  btnClass: 'btn-blue',
                  action: function() {
                    var loader = $('body').lyearloading({
                      opacity: 0.2,
                      spinnerSize: 'lg'
                    });
                    self.attr('autocomplete', 'off').prop('disabled', true);

                    ajaxPostFun(self, ajax_url, form_data, loader);
                  }
                },
                cancel: {
                  text: '取消',
                  action: function() {}
                }
              }
            });
            return false;
          } else {
            form_data = form.find("input,select,textarea").serialize();
            self.attr("autocomplete", "off").prop("disabled", true);
          }
        }

        var loader = $('body').lyearloading({
          opacity: 0.2,
          spinnerSize: 'lg'
        });
        ajaxPostFun(self, ajax_url, form_data, loader);

        return false;
      }
    });

    // 通用ajax get请求
    jQuery(document).delegate('.ajax-get', 'click', function(){
      var self = $(this), tips = self.data('tips'), ajax_url = self.attr("href") || self.data("url");

      if (self.hasClass('confirm')) {
        $.confirm({
          title: '',
          content: tips || '确认要执行该操作吗？',
          type: 'orange',
          typeAnimated: true,
          buttons: {
            confirm: {
              text: '确认',
              btnClass: 'btn-blue',
              action: function() {
                var loader = $('body').lyearloading({
                  opacity: 0.2,
                  spinnerSize: 'lg'
                });
                self.attr('autocomplete', 'off').prop('disabled', true);

                ajaxGetFun(self, ajax_url, loader);
              }
            },
            cancel: {
              text: '取消',
              action: function() {}
            }
          }
        });
        return false;
      } else {
        var loader = $('body').lyearloading({
          opacity: 0.2,
          spinnerSize: 'lg'
        });
        self.attr('autocomplete', 'off').prop('disabled', true);

        ajaxGetFun(self, ajax_url, loader);
      }
      return false;
    });

    // POST提交处理
    function ajaxPostFun(selfObj, ajax_url, form_data, loader) {
      console.log('url==>'+ajax_url);
      console.log('form_data==>'+form_data);
      setTimeout(function() {
        loader.destroy();
        showNotify('修改成功，页面即将自动跳转~', 'success', 1000);
        selfObj.attr("autocomplete", "on").prop("disabled", false);
      }, 1e3);
      // 这里屏蔽get提交，js模拟返回成功，正常使用时请删除上面的内容，打开下面的注释代码
      /*
      jQuery.post(ajax_url, form_data).done(function(res) {
          loader.destroy();
          var res = eval('(' + res + ')');
          var msg = res.msg;
          if (200 == res.code) {
              if (res.url && !selfObj.hasClass('no-refresh')) {
                  msg += '页面即将自动跳转';
              }
              showNotify(msg, 'info');
              setTimeout(function () {
                  selfObj.attr("autocomplete", "on").prop("disabled", false);
                  return selfObj.hasClass("no-refresh") ? false : (res.url ? location.href = res.url : location.reload());
              }, 1500);
          } else {
              showNotify(msg, 'danger');
              selfObj.attr("autocomplete", "on").prop("disabled", false);
          }
      }).fail(function () {
          loader.destroy();
          showNotify('服务器发生错误，请稍后再试', 'danger');
          selfObj.attr("autocomplete", "on").prop("disabled", false);
      });
      */
    }

    // GET提交处理
    function ajaxGetFun(selfObj, ajax_url, loader) {
      console.log(ajax_url);
      setTimeout(function() {
        loader.destroy();
        showNotify('修改成功，页面即将自动跳转~', 'success', 1000);
        selfObj.attr("autocomplete", "on").prop("disabled", false);
      }, 1e3);
      // 这里屏蔽get提交，js模拟返回成功，正常使用时请删除上面的内容，打开下面的注释代码
      /*
      jQuery.get(ajax_url).done(function(res) {
          loader.destroy();
          var res = eval('(' + res + ')');
          var msg = res.msg;
          if (200 == res.code) {
              if (res.url && !selfObj.hasClass('no-refresh')) {
                  msg += '页面即将自动跳转';
              }
              showNotify(msg, 'info');
              setTimeout(function () {
                  selfObj.attr("autocomplete", "on").prop("disabled", false);
                  return selfObj.hasClass("no-refresh") ? false : (res.url ? location.href = res.url : location.reload());
              }, 1500);
          } else {
              showNotify(msg, 'danger');
              selfObj.attr("autocomplete", "on").prop("disabled", false);
          }
      }).fail(function () {
          loader.destroy();
          showNotify('服务器发生错误，请稍后再试', 'danger');
          selfObj.attr("autocomplete", "on").prop("disabled", false);
      });
      */
    }

    /*
     * 提取通用的通知消息方法
     * 这里只采用简单的用法，如果想要使用回调或者更多的用法，请查看lyear_js_notify.html页面
     * @param $msg 提示信息
     * @param $type 提示类型:'info', 'success', 'warning', 'danger'
     * @param $delay 毫秒数，例如：1000
     * @param $icon 图标，例如：'fa fa-user' 或 'glyphicon glyphicon-warning-sign'
     * @param $from 'top' 或 'bottom' 消息出现的位置
     * @param $align 'left', 'right', 'center' 消息出现的位置
     */
    function showNotify($msg, $type, $delay, $icon, $from, $align) {
      $type  = $type || 'info';
      $delay = $delay || 1000;
      $from  = $from || 'top';
      $align = $align || 'right';
      $enter = $type == 'danger' ? 'animated shake' : 'animated fadeInUp';

      jQuery.notify({
                icon: $icon,
                message: $msg
              },
              {
                element: 'body',
                type: $type,
                allow_dismiss: true,
                newest_on_top: true,
                showProgressbar: false,
                placement: {
                  from: $from,
                  align: $align
                },
                offset: 20,
                spacing: 10,
                z_index: 10800,
                delay: $delay,
                animate: {
                  enter: $enter,
                  exit: 'animated fadeOutDown'
                }
              });
    }
  });
</script>--%>
</body>
</html>